package com.showsu.editor.utils.sms;

import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.google.gson.Gson;
import darabonba.core.client.ClientOverrideConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.concurrent.CompletableFuture;

/**
 * @Author: William
 * @Description: 阿里云短信发送工具
 * @Date: Created in 10:54 上午 2023/3/21
 * @Modified By:
 */
@Slf4j
@Component
public class AliyunSMSUtil {

    @Value("${aliyun.smsAndOss.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.smsAndOss.accessKeySecret}")
    private String accessKeySecret;

    private SendSmsResponse sendSms(String signature, String aliyunTemplatCode,
                                                              String mobile, String templateParam) {
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId(accessKeyId)
                .accessKeySecret(accessKeySecret)
                //.securityToken("<your-token>") // use STS token
                .build());
        // Configure the Client
        AsyncClient client = AsyncClient.builder()
                .region("cn-zhangjiakou") // Region ID
                .credentialsProvider(provider)
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                .setEndpointOverride("dysmsapi.aliyuncs.com")
                        //.setConnectTimeout(Duration.ofSeconds(30))
                )
                .build();
        // Parameter settings for API request
        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                .signName(signature)
                .templateCode(aliyunTemplatCode)
                .phoneNumbers(mobile)
                .templateParam(templateParam)
                .build();
        CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
        try {
            return response.get();
        } catch (Exception e) {
            log.error("AliyunSMSUtil.sendSms(....) get result from aliyun error", e);
            return null;
        } finally {
            client.close();
        }
    }

    /**
     * 发送验证码短信
     * @param mobile 手机号
     * @param code 验证码
     * @param aliyunTemplatCode 阿里云短信模版编码
     * @param signature 签名
     * @return
     */
    public Boolean send(String mobile, String code, String aliyunTemplatCode, String signature) {
        SendSmsResponse resp = sendSms(signature, aliyunTemplatCode, mobile, "{\"code\":\"" + code + "\"}");
        if (resp == null) {
            return false;
        }
        log.info("AliyunSMSUtil.send() params mobile:{},code:{},templatCode:{},signature:{}，响应结果:{}",
                mobile, code, aliyunTemplatCode, signature, new Gson().toJson(resp));
        if (resp.getBody() != null && StringUtils.isNotBlank(resp.getBody().getCode())
                && "OK".equals(resp.getBody().getCode())) {
            return true;
        }
        return false;
    }

    /**
     * 发送业务通知短信
     * @param mobile 手机号
     * @param name 资源名称
     * @param num 资源余额
     * @param aliyunTemplatCode 阿里云短信模版编码
     * @param signature 签名
     * @return
     */
    public Boolean sendNotice(String mobile, String name, String num, String aliyunTemplatCode, String signature) {
        SendSmsResponse resp = sendSms(signature, aliyunTemplatCode, mobile,
                "{\"name\":\"" + name + "\", \"num\": \"" + num +"\"}");
        if (resp == null) {
            return false;
        }
        log.info("AliyunSMSUtil.sendNotice() params mobile:{},name:{},num:{},templatCode:{},signature:{}，响应结果:{}",
                mobile, name, num, aliyunTemplatCode, signature, new Gson().toJson(resp));
        if (resp.getBody() != null && StringUtils.isNotBlank(resp.getBody().getCode())
                && "OK".equals(resp.getBody().getCode())) {
            return true;
        }
        return false;
    }

    /**
     * 发送业务通知短信
     * @param mobile 手机号
     * @param num 资源代码
     * @param aliyunTemplatCode 阿里云短信模版编码
     * @param signature 签名
     * @return
     */
    public Boolean sendNotice2(String mobile, String num, String aliyunTemplatCode, String signature) {
        try {
            SendSmsResponse resp = sendSms(signature, aliyunTemplatCode, mobile, "{\"num\": \"" + num +"\"}");
            if (resp == null) {
                return false;
            }
            log.info("AliyunSMSUtil.sendNotice2() params mobile:{},num:{},templatCode:{},signature:{}，响应结果:{}",
                    mobile, num, aliyunTemplatCode, signature, new Gson().toJson(resp));
            if (resp.getBody() != null && StringUtils.isNotBlank(resp.getBody().getCode())
                    && "OK".equals(resp.getBody().getCode())) {
                return true;
            }
        } catch (Exception e) {
            log.error("AliyunSMSUtil.sendNotice2() error mobile:{},num:{},templatCode:{},signature:{}",
                    mobile, num, aliyunTemplatCode, signature, e);
        }
        return false;
    }
}
